package com.wp.controller;

import com.wp.domain.Person;
import com.wp.service.PersonService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/person")
public class PersonController {

    @Resource
    private PersonService service;

    // 查询全部
    @GetMapping("/list")
    public ModelAndView findAll(ModelAndView modelAndView){

        List<Person> people = service.findAll();

        modelAndView.addObject("list",people);
        // 显示视图位置
        modelAndView.setViewName("index");

        return modelAndView;
    }

    // 添加信息
    @PostMapping("/add")
    public String add(Person person){
        int add = service.add(person);
        if (add>0){
            return "redirect:/person/list";
        }else {
            return null;
        }
    }

    // 删除信息
    @DeleteMapping("/del/{id}")//rest思想
    @ResponseBody
    public String del(@PathVariable(name = "id") Integer id){
        System.out.println(id);
        int del = service.del(id);

        if (del>0){
            return "{\"status\":\"success\"}";
        }else{
            return null;
        }
    }

    // 按编号插叙
    @GetMapping("/findById/{id}")  //PathVariable注解》》将url中的{id}占位符绑定到方法参数上
    public String findById(Model model,@PathVariable(name = "id") Integer id){

       Person person = service.findById(id);

       model.addAttribute("findById",person);

       return "upd";
    }

    // 修改信息
    @PostMapping("/update")
    public String upd(Person person){

        int upd = service.upd(person);

        if (upd>0){
            return "redirect:/person/list";
        }
        return null;
    }
}
